//
// Created by xu on 2024/11/14.
//

#include <stdio.h>
#include <stdbool.h>
#include <SDL.h>
#include <SDL_image.h>

SDL_Window *window;
SDL_Surface *wSurface;
SDL_Surface *pngSurface;
// 初始化
bool init() {
    bool success = true;
    int ret;
    ret = SDL_Init(SDL_INIT_VIDEO);
    if (ret < 0) {
        printf("初始化SDL失败！Error:%s\n", SDL_GetError());
        success = false;
        goto exit;
    }

    window = SDL_CreateWindow("SDL EXTENSION", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480,
                              SDL_WINDOW_SHOWN);
    if (window == NULL) {
        printf("创建窗口失败！Error:%s\n", SDL_GetError());
        success = false;
        goto exit;
    }
    int imgFlags = IMG_INIT_PNG;
    if (!(IMG_Init(imgFlags) & imgFlags)) {
        printf("图片加载器初始化失败！Error:%s\n", SDL_GetError());
        success = false;
        goto exit;
    }
    wSurface = SDL_GetWindowSurface(window);
    exit:
    return success;
}

SDL_Surface *loadSurface(const char *input_file) {
    SDL_Surface *optimizedSurface = NULL;
    SDL_Surface *loadedSurface = IMG_Load(input_file);
    if (loadedSurface == NULL) {
        printf("图片加载失败！Error:%s\n", IMG_GetError());
    } else {
        optimizedSurface = SDL_ConvertSurface(loadedSurface, wSurface->format, 0);
        if (optimizedSurface == NULL) {
            printf("图片优化失败！Error:%s\n", SDL_GetError());
        }
        SDL_FreeSurface(loadedSurface);
    }
    return optimizedSurface;
}

bool loadMedia() {
    bool success = true;
    pngSurface = loadSurface("qiuqiu.png");
    if (pngSurface == NULL) {
        success = false;
    }
    return success;
}

void close() {
    SDL_FreeSurface(pngSurface);
    pngSurface = NULL;
    SDL_DestroyWindow(window);
    window = NULL;

    IMG_Quit();
    SDL_Quit();
}

int main(int argc, char *argv[]) {
    if (!init()) {
        goto exit;
    }
    if (!loadMedia()) {
        goto exit;
    }

    bool quit = false;
    SDL_Event e;
    while (!quit) {
        while (SDL_PollEvent(&e) != 0) {
            if (e.type == SDL_QUIT) {
                quit = true;
            }
        }

        SDL_BlitSurface(pngSurface, NULL, wSurface, NULL);
        SDL_UpdateWindowSurface(window);
    }

    exit:
    close();
    return 0;
}